<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); 

class OneToMany extends codexforms{
    var $CI,$iteration,$local_table,$foreign_table,$primary_key,$display_field;
    var $definition_exists,$config;

    function OneToMany($name,$params){
        $this->CI = &get_instance();
        $params['params']['multiple'] = true;
        $params['params']['table'] = $name;
        $this->iteration = (isset($params['iteration']))? $params['iteration'] : 0;
        $this->primary_key = (isset($params['primary_key']))? $params['primary_key'] : 'id';

        codexforms::initiate($name,$params);

        if(isset($this->params['display_field']))
            $this->display_field = $this->params['display_field'];

        $this->local_table = $this->CI->codexadmin->db_table;
        $this->foreign_table = $name;

        if(file_exists(APPPATH.$this->CI->config->item('codex_definitions_dir').$this->name.'.yml')){
            $this->CI->load->library('spyc');
            $this->config = $this->CI->spyc->YAMLLOAD($this->CI->config->item('codex_definitions_dir').$this->name.'.yml');
            $this->definition_exists = true;
        }
        else
            $this->definition_exists = false;

    }
    function getFieldName(){
        return NULL;
    }
    function prepForDisplay($value){
        /*
         * To display the list of ingredients, we need to get the list of links, then for each, get the name of the foreign primary key.
         */
        $query = $this->CI->db->get_where($this->foreign_table,array($this->local_table.'_id'=>$this->CI->codexadmin->active_id));
        $list = array();
        foreach($query->result() as $link){
            $list[] = $link->{$this->display_field};
        }
            return implode(', ',$list);
    }
    function prepForDb($value){
        return NULL;
    }
    function prepForDelete(){
        /*
         * When a recipe is deleted, we need to delete all the rows in the linkage table that refer to it.
         */
        
        //Update the foreign table setting the id of the local table to NULL wherever the row in the foreign table refers to the row being deleted.
        $this->CI->db->update($this->foreign_table,array($this->local_table.'_id'=>-1),array($this->local_table.'_id'=>$this->CI->input->post($this->CI->codexadmin->primary_key)));
    }
    function postInsertHook($data){
        $new_items = $this->CI->input->post($this->foreign_table);
        $selected_items = $this->CI->input->post($this->foreign_table.'_selected_values');

        if($new_items = $this->CI->input->post($this->foreign_table) AND is_array($new_items) AND count($new_items) > 0){
            foreach($new_items as $row){
                $row[$this->local_table.'_id'] = $this->CI->codexadmin->active_id;
                $this->CI->db->insert($this->foreign_table,$row);
                if($this->CI->db->affected_rows() == 0)
                    show_error('There was an error inserting new item into foreign table.');
            }
        }

        if($selected_items AND is_array($selected_items))
            foreach($selected_items as $foreign_id){
                $this->CI->db->update($this->foreign_table,array($this->local_table.'_id'=>$this->CI->codexadmin->active_id),
                                                           array('id'=>$foreign_id));
            } 
    }
    function postEditHook ($data){ 
        $this->prepForDelete();
        $this->postInsertHook($data);
    }

    function getHTMLForForeignTable (){ 
        $this->CI->codexsession->keep_flashdata('form_id');
        if($this->definition_exists){
            $config = $this->config['form_setup'];
            $form = new codexforms();
            foreach($config as $name=>$val){
                $config[$name]['element_name'] = $this->name.'['.$this->iteration.']['.$name.']';
            }
            $form->setup($config);
            echo $form->getHTML();
        }
        else{
            $this->CI->codexsession->keep_flashdata('form_id');
            $table = $this->name;
            echo $this->CI->codexforms->getHTMLForTable($table,$table.'['.$this->iteration.'][',']');
        }
    }

    function getFieldList(){
        if(array_key_exists('table_fields',$this->params)){
            return explode(',',$this->params['table_fields']);
        }
        else{
            return $this->CI->db->list_fields($this->foreign_table);
        }
    }
    function setValue($new_val){
        $query = $this->CI->db->get_where($this->foreign_table,array($this->local_table.'_id'=>$this->CI->codexadmin->active_id));
        $name = $this->primary_key;
        foreach($query->result_array() as $link){
            $this->value[] = $link[$name];
        }
    }
	function getHTML()
    {
        $url =  site_url(strtolower($this->CI->codexadmin->controller_name).'/pluginCallback/').'/';
        $js = <<<EOT
        \$(document).ready(function() {
            \$('.codex-relational').append('<div style="width:50%;margin-bottom:15px"><a class="codex-relational-anchor form-element-text" href="#">Add new</a></div>');
            \$('.codex-relational-anchor').bind('click',function(){
                \$(this).parent().before('<div class="codex-relational-form"><a class="codex-relational-form-close" href="#">Close</a></div>');
                var dropdown_name = \$(this).parent().prevAll('input[name=relational_table_name]').attr('value');
                var div_before_link = \$(this).parent().prev();
                var iteration = \$("*").index( this );

                \$(this).ajaxStart(function() { 
                    \$(this).parent().parent().children('.loading').show();
                }).ajaxStop(function() { 
                    \$(this).parent().parent().children('.loading').hide();
                }); 
                 
                \$.post('$url' + dropdown_name, { 'plugin': 'onetomany', 'action': 'getHTMLForForeignTable', 'params':'iteration:'+iteration }, function(data) { 
                    div_before_link.append(data); 
                }); 

                \$('.codex-relational-form-close').bind('click',function(){
                    \$(this).parent().empty();
                    return false;
                });
                return false;
            });
        });
EOT;
        $html = "";
        $this->CI->codextemplates->inlineJS('relational-plugin',$js);

        $html .= $this->prefix;

        $html .= $this->getMessage($this->name);
        $html .= ' <label for="'.$this->name.'">
                    '.$this->label.'
                   </label>';
        $query = $this->CI->db->get($this->foreign_table);

        $list = array();
        $preselected_values = $this->CI->db->get_where($this->foreign_table,array($this->local_table.'_id'=>$this->CI->codexadmin->active_id));
        $name = $this->primary_key;
        foreach($preselected_values->result_array() as $link){
            $list[] = $link[$name];
        }

        if($this->definition_exists)
            $display_fields = isset($this->config['display_fields']) ? $this->config['display_fields'] : array_keys($this->config['form_setup']);
        else
            $display_fields = $this->getFieldList();

        $html .='<div class="codex-relational">';
            $html .='<table style="width:75%" class="codex-table"';
            $html .=$this->getAttributes($this->attributes).'>';
                $html .='<tr class="header-row"><th></th>';
                foreach($display_fields as $field){
                    $html .='<th>'.humanize($field).'</th>';
                }
                $html .='</tr>';
                $i = 0;
                foreach($query->result() as $row){
                    if($i % 2 == 0)
                        $html .= '<tr class="even"><td>';
                    else
                        $html .= '<tr class="odd"><td>';
                    
                    $html .= '<input type="checkbox" name="'.$this->name.'_selected_values[]" value="'.$row->{$this->primary_key}.'"';
                    if(count($list) > 0 AND in_array($row->{$this->primary_key},$list))
                        $html .= ' checked';
                    $html .= '></td>';
                    foreach($this->getFieldList() as $field){
                        $html .='<td>'.$row->$field.'</td>';
                    }
                    $html .='</tr>';
                    $i++;
                }
                $html .='</tr>';
            $html .='</table>';
            $html .='<input type="hidden" name="'.$this->name.'" value="">';
            $html .='<input type="hidden" name="relational_table_name" value="'.$this->foreign_table.'">';

            $html .= '<div class="loading">
                           <img src="'.$this->CI->config->item('codex_asset_folder').'images/spinner.gif"> Loading...
                      </div>
                </div> ';
        $html .= $this->suffix;
		
		return $html;
	}
}

?>
